<?php
/**
 * @author Jumper
 * date: 2021/04/15
 */
namespace App\Chat\Core;

use MessagePack\MessagePack;
use App\Exception\PacketException;
use App\Constants\ErrorCode;

/**
 * 数据打包、解包处理
 */
class Packet
{
    /**
     * 格式化打包数据
     */
    public static function format($code, $message, $data)
    {
        return [
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ];
    }

    /**
     * 打包数据
     */
    public static function encode($data, $format='msgpack', $type='tcp')
    {
        if ($type == 'tcp') {
            $sendStr = $data;
            if ($format == 'msgpack') {
                $sendStr = MessagePack::pack($data);
            }
            
            $sendStr = pack('N', strlen($sendStr)) . $sendStr;
            return $sendStr;
        } else {
            throw new PacketException(ErrorCode::PACKET_ERROR, 'packet encode error type:' . $type);
        }
    }
    
    /**
     * 解包数据
     */
    public static function decode($str, $format='msgpack')
    {
        $header = substr($str, 0, 4);
        if (strlen($header) != 4) {
            throw new PacketException(ErrorCode::PACKET_ERROR, 'packet decode error');
        }

        $len = unpack('Nlen', $header);
        $len = $len['len'];
        $result = substr($str, 4);
        if ($len != strlen($result)) {
            throw new PacketException(ErrorCode::PACKET_ERROR, 'packet decode error length');
        }

        if ($format == 'msgpack') {
            $result = MessagePack::unpack($result);
        }
        if (empty($result)) {
            throw new PacketException(ErrorCode::PACKET_ERROR, 'packet decode data empty');
        }

        return $result;
    }
}